package com.pxmeta.app.controller.game;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pxmeta.audio.entity.Music;
import com.pxmeta.audio.entity.MusicUserLike;
import com.pxmeta.audio.entity.dto.ChooseMusicDTO;
import com.pxmeta.audio.entity.dto.LikeMusicDTO;
import com.pxmeta.audio.service.IMusicService;
import com.pxmeta.audio.service.IMusicUserLikeService;
import com.pxmeta.chat.entity.vo.HotMusicVO;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.common.utils.agora.AgoraClient;
import com.pxmeta.party.entity.PartyMusicChoose;
import com.pxmeta.party.entity.dto.MusicChooseDTO;
import com.pxmeta.party.service.IPartyMusicChooseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/music")
@Api(tags = "音乐", value = "音乐")
@RequiredArgsConstructor
public class MusicController {
    private final IMusicUserLikeService musicUserLikeService;
    private final IMusicService musicService;
    private final AgoraClient agoraClient;
    private final IPartyMusicChooseService partyMusicChooseService;

    @ApiOperation("收藏音乐")
    @PostMapping("/likeMusic")
    public AjaxResult likeMusic(@RequestBody LikeMusicDTO dto){
        Long userId = SecurityUtils.getUserId();
        Long musicId = dto.getMusicId();
        MusicUserLike musicUserLike = new MusicUserLike();
        musicUserLike.setMusicId(musicId);
        musicUserLike.setUserId(userId);
        musicUserLikeService.save(musicUserLike);
        return AjaxResult.success();
    }


    @ApiOperation("用户点歌")
    @PostMapping("/chooseMusic")
    public AjaxResult chooseMusic(@RequestBody ChooseMusicDTO dto){
        Long userId = SecurityUtils.getUserId();
        Long musicId = dto.getMusicId();
        Long partyId = dto.getPartyId();
        partyMusicChooseService.chooseMusic(userId, partyId, musicId);
        return AjaxResult.success();
    }


    @ApiOperation("获取点歌列表")
    @GetMapping("/getChooseMusicList")
    public AjaxResult<List<MusicChooseDTO>> getChooseMusicList(@RequestParam Long partyId){
        List<MusicChooseDTO> list = partyMusicChooseService.getChooseMusicList(partyId);
        return AjaxResult.success(list);
    }


    @ApiOperation("从播放列表中移出歌曲")
    @DeleteMapping("/removeChooseMusic/{id}")
    public AjaxResult removeChooseMusic(@PathVariable Long id){
        partyMusicChooseService.removeById(id);
        return AjaxResult.success();
    }




    @GetMapping("/getLikeList")
    @ApiOperation("获取收藏列表")
    public AjaxResult<List<Music>> getLikeList(@RequestParam(defaultValue = "1",required = false) Integer page,
                                  @RequestParam(defaultValue = "10",required = false) Integer size){

        Long userId = SecurityUtils.getUserId();
        List<Music> musicList = musicUserLikeService.getLikeMusicList(userId, page, size);
        return AjaxResult.success(musicList);
    }

    @GetMapping("/getRecommendMusic")
    @ApiOperation("获取推荐音乐列表")
    public AjaxResult<List<Music>> getRecommendMusic(){
        List<Music> musicList = Lists.newLinkedList();
        HashMap<String, String> param = Maps.newHashMap();
        param.put("hotType","3");
        JSONObject result = agoraClient.doGetForMusic("/ktv-service/api/serv/song-hot", param);
        String listStr = result.getString("list");
        List<HotMusicVO> hotMusicVOList = JSONObject.parseArray(listStr, HotMusicVO.class);

        List<Long> hotMusicIds = hotMusicVOList.stream().map(HotMusicVO::getSongCode).collect(Collectors.toList());

        musicList = musicService.listByIds(hotMusicIds);
        Collections.shuffle(musicList);

        List<Music> recommendList = musicList.stream().limit(3).collect(Collectors.toList());

        return AjaxResult.success(recommendList);
    }


    @GetMapping("/getMusicList")
    @ApiOperation("获取音乐列表")
    public AjaxResult getMusicList(@RequestParam(required = false, defaultValue = "false") Boolean isHot,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam(required = false,defaultValue = "1") Integer page,
                                   @RequestParam(required = false, defaultValue = "10") Integer size,
                                   @RequestParam(required = false) Integer songType){

        Long userId = SecurityUtils.getUserId();

        List<Music> musicList = Lists.newLinkedList();
        if (isHot){
            HashMap<String, String> param = Maps.newHashMap();
            param.put("hotType","3");
            JSONObject result = agoraClient.doGetForMusic("/ktv-service/api/serv/song-hot", param);
            String listStr = result.getString("list");
            List<HotMusicVO> hotMusicVOList = JSONObject.parseArray(listStr, HotMusicVO.class);

            List<Long> hotMusicIds = hotMusicVOList.stream().map(HotMusicVO::getSongCode).collect(Collectors.toList());

             musicList = musicService.listByIds(hotMusicIds);
        }else {
            LambdaQueryWrapper<Music> wrapper = Wrappers.lambdaQuery();
            if (songType != null){
                wrapper.eq(Music::getType, songType);
            }
            if (StringUtils.isNotBlank(keyword)){
                wrapper.like(Music::getName, keyword).or().like(Music::getSinger, keyword);
            }
            musicList = musicService.page(new Page<>(page, size), wrapper).getRecords();
        }

        List<Long> musicIds = musicList.stream().map(Music::getId).collect(Collectors.toList());
        List<Long> likeMusicIds = musicUserLikeService.getByMusicIds(userId, musicIds).stream().map(MusicUserLike::getMusicId).collect(Collectors.toList());

        musicList.forEach(m-> m.setIsLike(likeMusicIds.contains(m.getId())));
        return AjaxResult.success(musicList);
    }



}
